package com.rogue.blog.service.image.impl;

import com.rogue.blog.service.image.ImageUploadService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * Created by 86101 on 2018-09-26.
 */
@Service
public class ImageUploadServiceImpl implements ImageUploadService {

    private final static Logger logger = LoggerFactory.getLogger(ImageUploadServiceImpl.class);

    @Value("${upload.image.location}")
    private String imageUploadLocation;

    @Override
    public String uploadImage(MultipartFile multipartFile) throws IOException {
        String originalFilename = multipartFile.getOriginalFilename();
        String relativePath = UUID.randomUUID().toString() + "/" + originalFilename;
        String imageUploadPath = imageUploadLocation + relativePath;
        File imageFile = new File(imageUploadPath);
        File imageFileDir = imageFile.getParentFile();
        if (!imageFileDir.exists()) {
            imageFileDir.setReadable(true);
            imageFileDir.setWritable(false);
            imageFileDir.setExecutable(true);
            imageFileDir.mkdirs();
        }
        imageFile.setReadable(true);
        imageFile.setWritable(false);
        imageFile.setExecutable(false);
        multipartFile.transferTo(imageFile);
        logger.info("ImageUploadServiceImpl.uploadImage success.Path: " + imageUploadPath);
        return relativePath;
    }

    @Override
    public File getImage(String relativePath) {
        String imageUploadPath = imageUploadLocation + relativePath;
        return new File(imageUploadPath);
    }
}
